<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装 AJAX 请求</title>
</head>
<body>
    <script>
        // $.get(url, data, fn)
        // $.post(url, data, fn);

        const $ = {
            get(url, data, fn){
                //发送 AJAX 请求
                let x = new XMLHttpRequest();
                //处理参数  {a: 100, b: 200}  ===> a=100&b=200
                let str = '';
                for(let i in data){ // for...in 循环
                    str += `${i}=${data[i]}&`;
                }
                str = str.slice(0, -1); // a=10&b=20&
                //初始化
                x.open('get', url+'?'+str); // http://127.0.0.1/server?a=100&b=200
                //发送
                x.send();
                //处理
                x.onreadystatechange = function(){
                    if(x.readyState === 4){
                        //处理响应结果
                        fn(x.response);
                    }
                }
            },
            post(url, data, fn){
                //发送 AJAX 请求
                let x = new XMLHttpRequest();
                //处理参数  {a: 100, b: 200}  ===> a=100&b=200
                let str = '';
                for(let i in data){ // for...in 循环
                    str += `${i}=${data[i]}&`;
                }
                str = str.slice(0, -1); //
                //初始化
                x.open('post', url); // 
                //设置请求头
                x.setRequestHeader('content-type','application/x-www-form-urlencoded');
                //发送
                x.send(str);
                //处理
                x.onreadystatechange = function(){
                    if(x.readyState === 4){
                        //处理响应结果
                        fn(x.response);
                    }
                }
            }
        };

        //调用
        // $.get('http://127.0.0.1/server', {a: 100, b: 200}, function(data){
        //     //处理响应体
        //     console.log(data)
        // });
        $.post('http://127.0.0.1/server', {a: 100, b: 200}, function(data){
            //处理响应体
            console.log(data)
        });
        



    </script>
</body>
</html>